/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tolls;

import avenue.Session;
import java.awt.Toolkit;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import model.Card;
import model.Payment;
import model.Vehicle;

/**
 *
 * @author tasos
 */
public class PayForm extends javax.swing.JDialog {

    /**
     * Creates new form PayForm
     */
    public PayForm(java.awt.Frame parent, boolean modal, Vehicle v) {
        super(parent, modal);
        em = Session.emf.createEntityManager();
        em.getTransaction().begin();
        if (v != null) {
            vehicle = v;
            card = v.getCardId();
        }
        initComponents();
        if (v != null) {
            regNumberTF.setEnabled(false);
            cardIdTF.setEnabled(false);
            searchButton.setVisible(false);
        }
        this.setLocationRelativeTo(null);
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("images/pass.jpg")));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        card1 = card;
        vehicle1 = vehicle;
        cardIdTF = new javax.swing.JTextField();
        regNumberLabel = new javax.swing.JLabel();
        regNumberTF = new javax.swing.JTextField();
        payButton = new javax.swing.JButton();
        balanceLabel = new javax.swing.JLabel();
        cardBalanceTF = new javax.swing.JTextField();
        paymentLabel = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        newBalanceTF = new javax.swing.JTextField();
        cancelButton = new javax.swing.JButton();
        paymentTF = new javax.swing.JTextField();
        newBalanceLabel = new javax.swing.JLabel();
        cardIdLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Πληρωμή Κάρτας");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, card1, org.jdesktop.beansbinding.ELProperty.create("${barcode}"), cardIdTF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        regNumberLabel.setText("Αρ. Πινακίδας : ");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, vehicle1, org.jdesktop.beansbinding.ELProperty.create("${regNumber}"), regNumberTF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        payButton.setText("Πληρωμή");
        payButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                payButtonActionPerformed(evt);
            }
        });

        balanceLabel.setText("Υπόλοιπο : ");

        cardBalanceTF.setEditable(false);
        cardBalanceTF.setEnabled(false);
        cardBalanceTF.setFocusable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, card1, org.jdesktop.beansbinding.ELProperty.create("${balance}"), cardBalanceTF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        paymentLabel.setText("Ποσό Πληρωμής :  ");

        searchButton.setText("Αναζήτηση");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        newBalanceTF.setEditable(false);
        newBalanceTF.setEnabled(false);
        newBalanceTF.setFocusable(false);

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        paymentTF.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                paymentTFCaretUpdate(evt);
            }
        });

        newBalanceLabel.setText("Νέο Υπόλοιπο : ");

        cardIdLabel.setText("Αρ. Κάρτας : ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(balanceLabel)
                    .addComponent(newBalanceLabel)
                    .addComponent(paymentLabel)
                    .addComponent(regNumberLabel)
                    .addComponent(cardIdLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cardBalanceTF)
                    .addComponent(paymentTF)
                    .addComponent(newBalanceTF)
                    .addComponent(regNumberTF)
                    .addComponent(cardIdTF)
                    .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(payButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cardIdLabel)
                    .addComponent(cardIdTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(regNumberLabel)
                    .addComponent(regNumberTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(searchButton)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(balanceLabel)
                    .addComponent(cardBalanceTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(paymentTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(paymentLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newBalanceLabel)
                    .addComponent(newBalanceTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(payButton)
                .addGap(18, 18, 18)
                .addComponent(cancelButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void payButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_payButtonActionPerformed

        if (newBalanceTF.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Μη έγκυρο νέο υπόλοιπο.",
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        }

        Double payment = Double.parseDouble(paymentTF.getText());
        Double oldBalance = card1.getBalance();
        Double newBalance = oldBalance + payment;

        if (payment < 10.0) {
            JOptionPane.showMessageDialog(this, "Το ποσό πληρωμής δεν μπορεί να είναι κάτω από 10 ευρώ.",
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Δημιουργία ενός αντικειμένου της κλάσης Payment
        Payment p = new Payment();
        em.persist(p);
        // Ανάθεση των πληροφοριών της πληρωμής στο αντικείμενο αυτό
        p.setCardId(card);
        p.setOldBalance(new BigDecimal(oldBalance));
        p.setPayment(new BigDecimal(payment));
        p.setPaymentTimestamp(new Date());
        p.setStationId(Session.getUser().getStationId());
        // Ανάθεση του νέου υπολοίπου στην κάρτα
        card1.setBalance(newBalance);
        em.merge(card1);

        // Οριστικοποίηση των αλλαγών;
        try {
            em.getTransaction().commit();
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_payButtonActionPerformed

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        if (card1 != null) {
            return;
        }

        // Έλεγχος των δεδομένων εισόδου
        if (regNumberTF.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Ο αριθμός κυκλοφορίας είναι κενός.",
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            cardBalanceTF.setText("");
            return;
        } else if (cardIdTF.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Ο αριθμός της κάρτας είναι κενός.",
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            cardBalanceTF.setText("");
            return;
        }

        String regNumber = regNumberTF.getText();
        Integer cardId;
        try {
            cardId = Integer.parseInt(cardIdTF.getText());
        } catch(NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Μη έγκυρος αριθμός κάρτας.",
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            cardBalanceTF.setText("");
            return;
        }

        // Αναζήτησε το όχημα με τον εν λόγω αριθμό πινακίδας και τον εν
        // λόγω αριθμό κάρτας
        Query query = em.createQuery("select v from Vehicle v where "
            + "v.regNumber = :regNumber and v.cardId.barcode = :cardId");

        query.setParameter("regNumber", regNumber);
        query.setParameter("cardId", cardId);

        try {
            // Εκτέλεση της επερώτησης
            vehicle1 = (Vehicle) query.getSingleResult();
            card1 = vehicle1.getCardId();
            cardBalanceTF.setText(card1.getBalance().toString());
        } catch(NoResultException ex) {
            // Το όχημα δεν βρέθηκε
            JOptionPane.showMessageDialog(this, "Ο συνδυασμός οχήματος/κάρτας δεν βρέθηκε.",
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            cardBalanceTF.setText("");
        } catch(Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(),
                "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            cardBalanceTF.setText("");
        }
    }//GEN-LAST:event_searchButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        try {
            em.getTransaction().rollback();
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void paymentTFCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_paymentTFCaretUpdate

        try {
            Double payment = Double.parseDouble(paymentTF.getText());
            if (payment < 0.0) {
                newBalanceTF.setText("");
            } else {
                Double newBalance = card1.getBalance() + payment;
                newBalanceTF.setText(newBalance.toString());
            }
        } catch(NumberFormatException ex) {
            newBalanceTF.setText("");
        }

    }//GEN-LAST:event_paymentTFCaretUpdate

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel balanceLabel;
    private javax.swing.JButton cancelButton;
    private model.Card card1;
    private javax.swing.JTextField cardBalanceTF;
    private javax.swing.JLabel cardIdLabel;
    private javax.swing.JTextField cardIdTF;
    private javax.swing.JLabel newBalanceLabel;
    private javax.swing.JTextField newBalanceTF;
    private javax.swing.JButton payButton;
    private javax.swing.JLabel paymentLabel;
    private javax.swing.JTextField paymentTF;
    private javax.swing.JLabel regNumberLabel;
    private javax.swing.JTextField regNumberTF;
    private javax.swing.JButton searchButton;
    private model.Vehicle vehicle1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private EntityManager em;
    private Vehicle vehicle;
    private Card card;
}
